import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:qilo/core/constants/app_colors.dart';
import '../../../core/constants/teach_video.dart';
import '../../../core/models/teach.dart';
import '../widgets/content_item_widget.dart';

class LearningHubPage extends StatefulWidget {
  final String? initialTab;

  const LearningHubPage({super.key, this.initialTab});

  @override
  State<LearningHubPage> createState() => _LearningHubPageState();
}

class _LearningHubPageState extends State<LearningHubPage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  int _currentIndex = 0;

  final List<String> _tabNames = ['Guitar', 'Piano', 'Drum Set'];
  final List<TeachType> _tabTypes = [
    TeachType.guitar,
    TeachType.piano,
    TeachType.drum,
  ];

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);

    // 根据传入的参数设置初始tab
    if (widget.initialTab != null) {
      switch (widget.initialTab!.toLowerCase()) {
        case 'guitar':
          _currentIndex = 0;
          break;
        case 'piano':
          _currentIndex = 1;
          break;
        case 'drum':
          _currentIndex = 2;
          break;
      }
      _tabController.index = _currentIndex;
    }

    _tabController.addListener(() {
      if (_tabController.indexIsChanging) {
        setState(() {
          _currentIndex = _tabController.index;
        });
      }
    });
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/one-bg.png'),
          fit: BoxFit.cover,
        ),
      ),
      child: Scaffold(
        backgroundColor: Colors.transparent,
        appBar: _buildAppBar(),
        body: Column(
          children: [
            _buildTabBar(),
            Expanded(
              child: TabBarView(
                controller: _tabController,
                children:
                    _tabTypes.map((type) => _buildContentList(type)).toList(),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建应用栏
  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      backgroundColor: Colors.transparent,
      elevation: 0,
      leading: IconButton(
        icon: Icon(Icons.arrow_back_ios, color: Colors.white, size: 24.sp),
        onPressed: () => Navigator.pop(context),
      ),
      title: Text(
        'Teaching',
        style: TextStyle(
          color: Colors.white,
          fontSize: 22.sp,
          fontWeight: FontWeight.w600,
        ),
      ),
      centerTitle: true,
    );
  }

  /// 构建标签栏
  Widget _buildTabBar() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(25.r),
        color: Colors.transparent,
      ),
      child: TabBar(
        controller: _tabController,
        indicator: BoxDecoration(
          borderRadius: BorderRadius.circular(25.r),
          color: AppColors.iconColor,
        ),
        indicatorSize: TabBarIndicatorSize.tab,
        dividerColor: Colors.transparent,
        labelColor: Colors.white,
        unselectedLabelColor: Colors.white,
        labelStyle: TextStyle(
          fontSize: 14.sp,
          fontFamily: 'Poppins',
          fontWeight: FontWeight.w700,
        ),
        unselectedLabelStyle: TextStyle(
          fontSize: 14.sp,
          fontFamily: 'Poppins',
          fontWeight: FontWeight.w700,
        ),
        tabs: _tabNames.map((name) => Tab(text: name)).toList(),
      ),
    );
  }

  /// 构建内容列表
  Widget _buildContentList(TeachType type) {
    final videos =
        TeachVideo.allTeach.where((teach) => teach.type == type).toList();

    if (videos.isEmpty) {
      return Center(
        child: Text(
          'No content available',
          style: TextStyle(
            color: Colors.white.withValues(alpha: 0.7),
            fontSize: 16.sp,
          ),
        ),
      );
    }

    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: GridView.builder(
        padding: EdgeInsets.only(top: 16.h, bottom: 100.h),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 1,
          childAspectRatio: 343 / 200,
          mainAxisSpacing: 16.h,
        ),
        itemCount: videos.length,
        itemBuilder: (context, index) {
          return ContentItemWidget(
            teach: videos[index],
            onTap: () => _handleVideoTap(videos[index]),
          );
        },
      ),
    );
  }

  /// 处理视频点击
  void _handleVideoTap(Teach teach) async {
    final result = await Navigator.pushNamed(
      context,
      '/media-presentation',
      arguments: teach,
    );

    // 如果返回值为 true，表示需要刷新列表
    if (result == true && mounted) {
      setState(() {
        // 刷新页面状态，重新构建列表
      });
    }
  }
}
